<?php

/**
 * Gère les actions liés à l'administration
 */
class AdminController {

    function __construct() {
        
    }

    /**
     * Récupère les administrateurs d'un projet
     * @param type $choice
     * @return type
     */
    public static function loadAdmin($choice) {
        switch ($choice) {
            case "projects":
                $list = Project::getProjectsOfMember(Authentification::getCurrentMemberId(), Authentification::getCurrentMemberStatut());
                if (Authentification::getCurrentMemberStatut() == Member::FULLADMIN)
                    return $list;
                else {
                    $result = Array();
                    foreach ($list as $p) {
                        if ($p->getUserType() == Project::ADMIN)
                            $result[] = $p;
                    }
                    return $result;
                }

                break;
            case "members":
                return Member::getMembers();
                break;

            default:
                break;
        }
    }

    /**
     * Function d'enregistrement des utilisateurs ou des projets
     */
    public static function save() {

        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case "saveUser":
                    $password = $_POST['form-password'];
                    $password = md5($password);  // Cryptage du mot de passe
                    
                    if (!empty($_POST['form-enabled']) && $_POST['form-enabled'] == "true")
                        $isEnabled = "1";
                    else
                        $isEnabled = "0";
                    
                    $member = new Member('null', $password, $_POST['form-login'], $_POST['form-email'], $_POST['form-first-name'], $_POST['form-last-name'], $_POST['form-address'], $_POST['form-company'], $_POST['form-city'], $_POST['form-zip'], $_POST['form-phone'], (isset($_POST['form-avatar'])) ? $_POST['form-avatar'] : null, $_POST['form-status'], $isEnabled);
                    $member->save();

                    break;

                case "updateUser":

                    $password = $_POST['form-update-password'];
                    $password = ($_POST['form-update-password'] == null) ? null : md5($password);  // Cryptage du mot de passe
                    if (!empty($_POST['form-update-enabled']) && ($_POST['form-update-enabled']) == "true") {
                        $isEnabled = "1";
                    }
                    else
                        $isEnabled = "0";
                    
                
                    Log::createLog($isEnabled);
                    $member = new Member($_POST['idMember'], $password, $_POST['form-update-login'], $_POST['form-update-email'], $_POST['form-update-first-name'], $_POST['form-update-last-name'], $_POST['form-update-address'], $_POST['form-update-company'], $_POST['form-update-city'], $_POST['form-update-zip'], $_POST['form-update-phone'], (isset($_POST['form-update-avatar'])) ? $_POST['form-update-avatar'] : null, $_POST['form-update-status'], $isEnabled);
                    $member->update();
                    break;

                case "deleteUser":
                    $member = Member::getMemberById($_POST['idMember']);
                    $member->delete();
                    break;
                case "getMember":
                    break;
                //echo "<meta http-equiv='Refresh' content='0;url=index.php?page=4'/>";
                case "saveProject":
                    $_SESSION["projectName"] = $_POST["form-projectname"];
                    
                    $search = array('â', 'à', 'é', 'è', 'ê', 'î', 'ô', 'û', 'ç', "\'", " ", '"', '?', '!', ',', '&');
                    $replace = array('a', 'a', 'e', 'e', 'e', 'i', 'o', 'u', 'c', '_', "_", '_', "_", "_", "_", "_");

                    $table_name = strtolower(str_replace($search, $replace, $_POST["form-projectname"]));
                    
                    $project = new Project('null', $_POST["form-projectname"], $table_name, "", "", $_POST["form-projectgraphe"], "", $_POST["form-projectnblign"]);
                    $project->save();
                    $project = Project::getProjectByName($_POST["form-projectname"]);
                    $admins = explode(",", $_POST['form-projectadmin']);
                    $users = explode(",", $_POST['form-projectuser']);
                    $project->saveProjectUserAdmin($admins, $users);

                    // creation table data = nom des colonnes data2 =  nom usuel des colonnes
                    $data = explode(";", $_POST['form-projectcolumn']);
                    $data2 = explode(";", $_POST['form-projectcolumnname']);
                    $project->createTableProject($data, $data2);

                    break;
                case "updateProject":

                    //Log::createLog("\n s'il te plait");
                    $_SESSION["projectName"] = $_POST["form-update-projectname"];

                    $project = new Project($_POST['idProject'], $_POST["form-update-projectname"], strtolower($_POST["form-update-projectname"]), "", "", $_POST["form-update-projectgraphe"], "", $_POST["form-update-projectnblign"]);

                    $project->update();
                    Log::createLog("update");

                    $project = Project::getProjectByName($_POST["form-update-projectname"]);
                    Log::createLog("get project");
                    $admins = explode(",", $_POST['form-update-projectadmin']);
                    $users = explode(",", $_POST['form-update-projectuser']);

                    $project->deleteProjectUserAdmin();
                    Log::createLog("delete");

                    $project->saveProjectUserAdmin($admins, $users);
                    Log::createLog("save");

                    $columnsCsv = explode(";", $_POST['form-update-projectcolumn']);
                    $columnsName = explode(";", $_POST['form-update-projectcolumnname']);
                    $columnsToDelete = explode(";", $_POST['form-update-projectcolumndelete']);


                    if ($columnsToDelete != "")
                        $project->deleteColumns($columnsToDelete);


                    $project->updateTableProject($columnsCsv, $columnsName);

                    break;

                case "deleteProject":
                    $project = Project::getProjectByID($_POST['idProject']);
                    $project->delete();
                    break;

                case "checkProject":
                    return Project::checkAvailability($_POST['name']);
                    Log::createLog("available : " . Project::checkAvailability($_POST['name']));
                    break;
                case "uploadImg":
                    Log::createLog("IMG!!");
                    AdminController::bp_checkins_handle_checkin_upload();
                    break;
                default :
                    //echo "<meta http-equiv='Refresh' content='0;url=index.php?page=4'/>";

                    break;
            }
        }
    }

    public static function bp_checkins_handle_checkin_upload() {

        if ($_POST['encodedimg']) {


            $imgresponse = array();
            $img = $_POST['encodedimg'];
            $img = str_replace('data:' . $_POST['imgtype'] . ';base64,', '', $img);
            $img = str_replace(' ', '+', $img);
            $data = base64_decode($img);
            $imgname = $_POST['imgname'];
            $filepath = 'public/img/' . $imgname;
            //Log::createLog($imgname);
            //Log::createLog($img);
            //Log::createLog($filepath);

            $success = file_put_contents($filepath, $data);
            if ($success) {
                if (file_exists('public/img/' . $_SESSION["projectName"] . ".png")) {

                    unlink('public/img/' . $_SESSION["projectName"] . ".png");
                }
                rename($filepath, 'public/img/' . $_SESSION["projectName"] . ".png");
                AdminController::thumbnailFromImage('public/img/' . $_SESSION["projectName"] . ".png", 'public/img/thumbs/', 87, 122);
                $_SESSION["projectName"] = "";
            } else {
                
            }
        } else {
            
        }
        /* if everything is ok, we send back url to thumbnail and to full image */
        echo json_encode($imgresponse);
        die();
    }

    public static function thumbnailFromImage($file_path, $dest_folder, $width, $height, $jpeg = false) {
        $file_name_complete = end(explode("/", $file_path));

        $file_explode = explode(".", $file_name_complete);
        $file_ext = array_pop($file_explode); // Extension du fichier
        $file_name = implode(".", $file_explode); // Nom sans extension

        $image_data = getimagesize($file_path);
        $image_ext = explode("/", $image_data["mime"]);
        $image_ext = $image_ext[1];

        $dest[0] = $width;
        $dest[1] = $height;

        $ratio_i = $image_data[0] / $image_data[1]; // Ratio de l'image initiale
        $ratio_th = $dest[0] / $dest[1]; // Ratio de l'image miniature

        if ($ratio_th >= 1) {
            if ($ratio_i >= 1) {
                if ($ratio_i >= $ratio_th) {
                    $ref_value = 1; // Utiliser la hauteur comme base
                } else {
                    $ref_value = 0; // Utiliser la largeur comme base
                }
            } else {
                $ref_value = 0; // Utiliser la largeur comme base
            }
        } else {
            if ($ratio_i >= 1) {
                $ref_value = 1; // Utiliser la hauteur comme base
            } else {
                if ($ratio_i <= $ratio_th) {
                    $ref_value = 0; // Utiliser la largeur comme base
                } else {
                    $ref_value = 1; // Utiliser la hauteur comme base
                }
            }
        }

        $sample[$ref_value] = ($image_data[$ref_value] * 80) / 100;
        $sample[!$ref_value] = ($sample[$ref_value] * $dest[!$ref_value]) / $dest[$ref_value];

        $offset[$ref_value] = ($image_data[$ref_value] * 10) / 100;
        $offset[!$ref_value] = ($image_data[!$ref_value] / 2) - ($sample[!$ref_value] / 2);

        // Création d'une image mémoire d'après l'image originale
        $img_tmp = call_user_func("imagecreatefrom" . $image_ext, $file_path);

        // Création d'une image mémoire pour la miniature
        $img_tmp_th = imagecreatetruecolor($dest[0], $dest[1]);

        // Redimensionne et copie l'image dans $img_tmp_th
        // imagecopyresampled($img_tmp_th, $img_tmp, 0, 0, $offset_x, $offset_y, $dest_w, $dest_h, $sample_w, $sample_h) ;
        imagecopyresampled($img_tmp_th, $img_tmp, 0, 0, $offset[0], $offset[1], $dest[0], $dest[1], $sample[0], $sample[1]);

        if (!$jpeg) {
            // Création d'un fichier vide pour mettre la miniature
            $newfile = fopen($dest_folder . $file_name_complete, "w");
            fclose($newfile);

            // Copie $img_virtual_th dans le fichier
            call_user_func("image" . $image_ext, $img_tmp_th, $dest_folder . $file_name_complete);
        } else {
            // Création d'un fichier vide pour mettre la miniature
            $newfile = fopen($dest_folder . $file_name . ".jpg", "w");
            fclose($newfile);

            // Copie $img_virtual_th dans le fichier
            call_user_func("imagejpeg", $img_tmp_th, $dest_folder . $file_name . ".jpg");
        }

        // Suppression des images mémoires
        imagedestroy($img_tmp);
        imagedestroy($img_tmp_th);
    }

}

?>
